package com.enbatis.mybatisplugs.component;

import com.alibaba.fastjson.JSONObject;
import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.entity.SysMsg;
import com.enbatis.mybatisplugs.entity.SysMsgRelUser;
import com.enbatis.mybatisplugs.entity.SysUser;
import com.enbatis.mybatisplugs.entity.dto.SysMsgDTO;
import com.enbatis.mybatisplugs.service.SysMsgRelUserService;
import com.enbatis.mybatisplugs.service.SysMsgService;
import com.enbatis.mybatisplugs.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
//
//@Component
//@RabbitListener(queues = "msg_send")
public class MsgReceiver {

    @Autowired
    private SysMsgService sysMsgService;
    @Autowired
    private SysMsgRelUserService sysMsgRelUserService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private WebSocket webSocket;

    @RabbitHandler
    public void msgReceive(String dtoJson) {
        SysMsgDTO dto = JSONObject.parseObject(dtoJson).toJavaObject(SysMsgDTO.class);
        SysMsg sysMsg = dto.getSysMsg();
        List<Long> userIds = dto.getUserIds();
        if (sysMsgService.insert(sysMsg)!=null){
              List<SysMsgRelUser> saveRel=new ArrayList<>();
            if (CollectionUtils.isEmpty(userIds)){

                List<SysUser> listAll = sysUserService.list(new Wrapper<>(new SysUser()).eq("company_id",sysMsg.getCompanyId()));
                for (SysUser user:listAll) {
                    SysMsgRelUser relUser = new SysMsgRelUser();
                    relUser.setCompanyId(sysMsg.getCompanyId());
                    relUser.setDeleted(0);
                    relUser.setMsgId(sysMsg.getId());
                    relUser.setUserId(user.getId());
                    saveRel.add(relUser);
                }

            }else{
                for (Long usd:userIds) {
                    SysMsgRelUser relUser = new SysMsgRelUser();
                    relUser.setCompanyId(sysMsg.getCompanyId());
                    relUser.setDeleted(0);
                    relUser.setMsgId(sysMsg.getId());
                    relUser.setUserId(usd);
                    saveRel.add(relUser);

                }
            }
          if (CollectionUtils.isNotEmpty(saveRel)){
             if (sysMsgRelUserService.saveBatch(saveRel)==saveRel.size()){
                 for (SysMsgRelUser msgRelUser:saveRel) {
                    webSocket.sendOneMessage(String.valueOf(msgRelUser.getUserId()),sysMsg.getName());
                 }
             }



          }
        }



    }
}
